package net.aiotos.common.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

@Slf4j
public class PostUrl {

    //http请求返回json
    public static String postMethod(String url,String param) throws Exception {
    	PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);

            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);

            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            throw e;
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
            	log.error("IO关闭异常");
            }
        }
        return result;
    }  
    
    /**
     * http文件上传
     * @param url
     * @param params
     * @return
     */
    public static String postMethod(String url, Map<String, String> params)
    {
        int SOCKET_TIME_OUT = 30000; // 超时时间
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig =
            RequestConfig.custom().setSocketTimeout(SOCKET_TIME_OUT).setConnectTimeout(SOCKET_TIME_OUT).build();// 设置请求和传输超时时间
        httpPost.setConfig(requestConfig);
        
        // 结果
        CloseableHttpResponse response = null;
        String content = "";
        HttpEntity reqEntity = null;
        
        try
        {
            if (null != params && !params.isEmpty())
            {
            	String file = params.get("content");
            	FileBody bin = new FileBody(new File(file));
            	StringBody drive_id = new StringBody(params.get("drive_id"),
            			ContentType.create("text/plain",Consts.UTF_8));
            	StringBody device_id = new StringBody(params.get("device_id"),
            			ContentType.create("text/plain",Consts.UTF_8));
            	reqEntity =  MultipartEntityBuilder.create()
            			.addPart("content", bin)
            			.addPart("drive_id", drive_id)
            			.addPart("device_id", device_id)
            			.build();
            	
            	// 将参数给post方法        
            	httpPost.setEntity(reqEntity);
                log.debug(reqEntity.toString());
            }
            // 执行post方法
            response = httpclient.execute(httpPost);
            if (null != response)
            {
                log.debug("===========================response:" + response);
            }
            if (null != response && response.getStatusLine().getStatusCode() == 200)
            {
                content = EntityUtils.toString(response.getEntity(), "UTF-8");
                log.debug(content);
            }
            else
            {
                log.error("======================================IceService构造方法向服务器登录发生异常  url:" + url);
            }
            EntityUtils.consume(reqEntity);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            log.error("======================================IceService构造方法向服务器登录发生异常  url:" + url);
            log.error(e.getMessage());
        }
        finally
        {
            try
            {
                if (null != response)
                {
                    response.close();
                }
                if (null != httpclient)
                {
                    httpclient.close();
                }
            }
            catch (IOException e)
            {
                log.error(e.getMessage());
            }
        }
        return content;
    }
     
    /**
     * http文件下载
     * @param url
     * @param destFileName
     * @throws IOException 
     * @throws ClientProtocolException 
     */
    public static String getFile(String url,String destFileName) {
    	 // 生成一个httpclient对象  
        CloseableHttpClient httpclient = HttpClients.createDefault();  
        HttpGet httpget = new HttpGet(url);  
        HttpResponse response = null;  
        HttpEntity entity =null;  
        InputStream in = null;  
        File file = null;  
        String content = "";
        try {  
        	response = httpclient.execute(httpget);
        	entity = response.getEntity();
        	in = entity.getContent(); 
        	file = new File(destFileName); 
            FileOutputStream fout = new FileOutputStream(file);  
            int l = -1;  
            byte[] tmp = new byte[1024];  
            while ((l = in.read(tmp)) != -1) {  
                fout.write(tmp, 0, l);  
                // 注意这里如果用OutputStream.write(buff)的话，图片会失真，大家可以试试  
            }  
            fout.flush();  
            fout.close();  
            
            if (null != response)
            {
                log.debug("===========================response:" + response);
            }
            if (null != response && response.getStatusLine().getStatusCode() == 200)
            {
                content = EntityUtils.toString(response.getEntity(), "UTF-8");
                log.debug(content);
            }
            else
            {
                log.error("======================================IceService构造方法向服务器登录发生异常  url:" + url);
            }
        }catch(Exception e){
        	e.printStackTrace();
        } finally {
        	try {
        		 // 关闭低层流。  
            	if (null != in) {
            		 in.close();
    			}
            	if (null != httpclient) {
            		httpclient.close(); 
    			}
			} catch (Exception e2) {
				e2.printStackTrace();
			} 
        }  
       return content;  
    }  
}
